package com.li.configserve.config.globalexception;

import com.li.configserve.domain.gloabreturn.ResponseInfo;
import com.li.configserve.domain.gloabreturn.ResultEnum;
import io.swagger.annotations.ApiModel;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于处理404、500错误
 *
 * @author MarLonBrando
 */
@RestController
@ApiModel(value = "全局ErrorHandler")
public class ErrorHandler implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @GetMapping(value = "/error")
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public ResponseInfo<Object> handleError(HttpServletRequest request) {
        ResponseInfo<Object> responseInfo = new ResponseInfo<>();
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        // 如果等于 404 错误，则抛出设定的枚举类中的错误信息
        if (HttpStatus.NOT_FOUND.value() == statusCode) {
            responseInfo.setMessage(ResultEnum.NOT_FOUNT_RESOURCE.getMessage());
            responseInfo.setCode(ResultEnum.NOT_FOUNT_RESOURCE.getCode());
            return responseInfo;
        } else if (HttpStatus.METHOD_NOT_ALLOWED.value() == statusCode) {
            // 405 post/get 请求
            responseInfo.setMessage(ResultEnum.REQUEST_WAY.getMessage());
            responseInfo.setCode(ResultEnum.REQUEST_WAY.getCode());
            return responseInfo;
        }
        // 如果非404，那就是500错误，则抛出设定的枚举类中的系统错误信息
        responseInfo.setMessage(ResultEnum.SYSTEM_ERROR.getMessage());
        responseInfo.setCode(ResultEnum.SYSTEM_ERROR.getCode());
        return responseInfo;
    }

}